package edu.luc.cs.trull.demo.task;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.UIManager;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import edu.luc.cs.trull.Component;
import edu.luc.cs.trull.Composite;
import edu.luc.cs.trull.Control;
import edu.luc.cs.trull.EmitComponent;
import edu.luc.cs.trull.Loop;
import edu.luc.cs.trull.Scheduling;
import edu.luc.cs.trull.Suspend;
import edu.luc.cs.trull.task.PooledTaskWorker;
import edu.luc.cs.trull.task.QueuedTaskWorker;
import edu.luc.cs.trull.task.DefaultTaskWorker;

/**
 * This example demonstrates how a task can be controlled and monitored 
 * using a simple user interface and a Trull component as the control logic.  
 */
public class SimpleDemo implements EventLabels {

  static final int MAX = 5000000;

  static final int INC = MAX / 100;

  public static void main(String[] args) throws Exception {

    UIManager.setLookAndFeel(
        UIManager.getCrossPlatformLookAndFeelClassName());

    BasicConfigurator.configure();
    Logger.getRootLogger().setLevel(Level.WARN);
//    Logger.getLogger(DefaultTaskWorker.class).setLevel(Level.DEBUG);
    Scheduling.setMode(Scheduling.SWINGFAST);

    final ControlPanel controlPanel = new ControlPanel();
    controlPanel.getProgressBar().setMaximum(MAX);

    // glue component for using Swing control panel in Trull
    final EmitComponent controlEmitter = new EmitComponent();

    // convert ActionEvents from control panel to PropertyChangeEvent
    controlPanel.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
      		controlEmitter.scheduleEvent(e.getActionCommand());
      }
    });

    // component wrapping around some task
    Component taskRunner = new DefaultTaskWorker(
//    Component taskRunner = new QueuedTaskWorker(
//    Component taskRunner = new PooledTaskWorker(
        new ProgressTask(new Count(MAX, INC), controlPanel.getProgressBar(), MAX));

    // hook it all together
    final Composite test = new Composite(new Component[] { 
      controlEmitter, 
      new Loop(
        new Control(START, 
          new Suspend(SUSPEND, RESUME, new Loop(taskRunner)), 
          STOP 
        )
      )
    });

    // put the control panel inside a frame
    final JFrame frame = new JFrame("Trull Simple Task Demo");
    frame.setContentPane(controlPanel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

    // start the Trull component
    Scheduling.getScheduler().start(test);
  }
}